package com.example.curatorzkdemo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.atomic.AtomicInteger;

public class TicketSalesTask implements Runnable{

    private AtomicInteger remain; // 共享资源

    private AtomicInteger soldCount = new AtomicInteger();

    private String trainNum; // 车次

    private String date; // 日期

    private InterProcessMutex lock; // ZooKeeper 分布式锁

    public TicketSalesTask(CuratorFramework client, String trainNum, String date, int totalNum) {
        this.trainNum = trainNum;
        this.date = date;
        this.remain = new AtomicInteger(totalNum);
        String locksPath = String.format("/%s_%s_locks", trainNum, date); // 不同日期、车次的售票任务应当使用不同的锁路径
        lock = new InterProcessMutex(client, locksPath);
    }

    @Override
    public void run() {
        while (true) {
            try {
                lock.acquire(); // 获取锁

                if (remain.get() > 0) {
                    remain.decrementAndGet();
                    soldCount.incrementAndGet();
                } else {
                    break;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    lock.release(); // 在 finally 块中释放锁
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public String getSoldResult() {
        return String.format("%s %s 次列车共卖出 %s 张车票", date, trainNum, soldCount.get());
    }
}
